package com.five.wisdomClass.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.five.wisdomClass.config.PaginationUtil;
import com.five.wisdomClass.entity.*;
import com.five.wisdomClass.mapper.PublicCourseMapper;
import com.five.wisdomClass.mapper.TakeCourseMapper;
import com.five.wisdomClass.mapper.TeacherMapper;
import com.five.wisdomClass.service.ITeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Slf4j
@Service
public class TeacherServiceImpl implements ITeacherService {

    @Autowired
    TeacherMapper teacherMapper;

    @Autowired
    PublicCourseMapper publicCourseMapper;
    @Autowired
    TakeCourseMapper takeCourseMapper;

    // 获取课程列表
    @Override
    public List<Course> getCourses(String teacherNumber) {
        Teacher teacher = teacherMapper.getTeacher(teacherNumber);
        if (teacher == null){
            return null;
        }
        // 获取教师编号
        List<Course> courseList = new ArrayList<>();
        // 获取公共课程和选修课程，添加到课程列表，一起返回
        List<Course> publicCourse = teacherMapper.getPublicCourse(teacherNumber);
        List<Course> takeCourse = teacherMapper.getTakeCourse(teacherNumber);
        courseList.addAll(publicCourse);
        courseList.addAll(takeCourse);
        return courseList;
    }

    // 获取课程学生信息
    @Override
    public IPage<Student> getCourseStudents(Integer currentPage, Integer size, String courseNumber) {
        Page<Student> pagerequest = new Page<>(currentPage,size);
        // 获取班级号
        if (courseNumber == null){
            return null;
        }
        // 公共课程
        if (teacherMapper.getClassId(courseNumber) != null ){
            String classId = teacherMapper.getClassId(courseNumber);
            // 获取班级名称
            if (classId == null){
                return null;
            }
            String className = teacherMapper.getClassName(classId);
            // 获取学生集合
            IPage<Student>  studentIpage = teacherMapper.selectStudents(pagerequest,className);
            return studentIpage;
        } else if (teacherMapper.getStudentNumbers(courseNumber) != null) {
            // 获取学号集合
            List<String> studentNumberList = teacherMapper.getStudentNumbers(courseNumber);
            // 获取学生集合
            List<Student> studentList = new ArrayList<>();
            for (String studentNumber : studentNumberList){
                studentList.add(teacherMapper.selectStudent(studentNumber));
            }

            // 分页
            Page<Student> page = new Page<>(currentPage, size);
            // 将查询到的学生列表（studentList）设置到分页对象中
            page.setRecords(studentList);
            page.setTotal(studentList.size());
            IPage<Student> studentIpage = page;
            return studentIpage;
        }else{
            return null;
        }
    }

    // 获取课程中请假的学生
    @Override
    public IPage<Leave> getCourseStudentLeave(Integer currentPage, Integer size, String courseNumber) {
        // 获取班级号
        if (courseNumber == null){
            return null;
        }
        // 公共课程
        if (teacherMapper.getClassId(courseNumber) != null ){
            String classId = teacherMapper.getClassId(courseNumber);
            // 获取班级名称
            if (classId == null){
                return null;
            }
            String className = teacherMapper.getClassName(classId);
            // 通过班级名称获得学号集合
            List<String>  studentsNumberList= teacherMapper.getClassStudentsNumber(className);
            List<Leave> leaveList = new ArrayList<>();
            for (String sNumber : studentsNumberList){
                leaveList.addAll(teacherMapper.getCourseStudentLeave(sNumber));
            }
           // 分页
//            Page<Leave> page = new Page<>(currentPage,size);
//            // 将查询到的学生列表（studentList）设置到分页对象中
//            page.setRecords(leaveList);
//            page.setTotal(leaveList.size());
//            page.setCurrent(currentPage);
//            page.setSize(size);
//            IPage<Leave> leavePage = page;
            return PaginationUtil.paginate(leaveList,currentPage,size);
            // 选修课程
        } else if (teacherMapper.getStudentNumbers(courseNumber) != null) {
            // 获取学号集合
            List<String> studentNumberList = teacherMapper.getStudentNumbers(courseNumber);
            List<Leave> leaveList = new ArrayList<>();
            for (String sNumber : studentNumberList){
                leaveList.addAll(teacherMapper.getCourseStudentLeave(sNumber));
            }
            // 分页
            return PaginationUtil.paginate(leaveList,currentPage,size);
        }else{
            return null;
        }
    }
//    // 获取学生请假列表
//    @Override
//    public IPage<Leave> getStudentLeaves(Integer currentPage, Integer size, String teacherNumber) {
//        if (teacherNumber == null){
//            return null;
//        }
//        List<Leave> leaveList = new ArrayList<>();
//        // 获取公共课程号
//        List<String> publicCourseNumberList = teacherMapper.getPublicCourseNumbers(teacherNumber);
//        if (!publicCourseNumberList.isEmpty()){
//            List<String> classIdList = new ArrayList<>();
//            // 通过课程号获得班级号集合
//            for (String publicCourseNumber : publicCourseNumberList){
//                classIdList.add(teacherMapper.getClassId(publicCourseNumber));
//            }
//            // 获取班级名称集合
//            List<String> classNameList = new ArrayList<>();
//            for (String classId : classIdList){
//                classNameList.add(teacherMapper.getClassName(classId));
//            }
//            // 遍历班级，获取学生学号集合
//            List<String> publicStudentNumbersList = new ArrayList<>();
//            for (String className : classNameList){
//                publicStudentNumbersList.addAll(teacherMapper.getStudentNumbersByClassName(className));
//                log.error(className + "++++++++++++");
//            }
//            // 通过学号查询请假列表
//            if (!publicStudentNumbersList.isEmpty()){
//                log.error("进!publicStudentNumbersList.isEmpty()了");
//                for (String studentNumber : publicStudentNumbersList){
//                    leaveList.addAll(teacherMapper.getStudentLeaves(studentNumber));
//                }
//            }
//        }
//        // 获取选修课程号列表
//        List<String> takeCourseNumberList  = teacherMapper.getTakeCourseNumbers(teacherNumber);
//        if (!takeCourseNumberList.isEmpty()){
//            // 获取选修课程学生学号集合
//            List<String> takeCourseStudentNumberList = new ArrayList<>();
//            for (String takeCourseNumber : takeCourseNumberList){
//                takeCourseStudentNumberList.addAll(teacherMapper.getStudentNumbers(takeCourseNumber));
//            }
//            // 通过学号查询请假列表
//            if (!takeCourseStudentNumberList.isEmpty()){
//                log.error("进!takeCourseStudentNumberList.isEmpty()了");
//                for (String studentNumber : takeCourseStudentNumberList){
//                    leaveList.addAll(teacherMapper.getStudentLeaves(studentNumber));
//                }
//            }
//        }
//        // 进行分页
//        Page<Leave> page = new Page<>(currentPage, size);
//        // 将查询到的学生请假列表（leaveList）设置到分页对象中
//        page.setRecords(leaveList);
//        page.setTotal(leaveList.size());
//        IPage<Leave> leavePage = page;
//        return leavePage;
//    }




    // 发布签到
    @Override
    public boolean postSignIn(Course course) {
        int s = 0;
        // 获取学生学号集合
        String classId = teacherMapper.getClassId(course.getCourseNumber());
        String className = teacherMapper.getClassName(classId);
        // 通过班级名获取
        List<String> studentNumberList = new ArrayList<>();
        studentNumberList.addAll(teacherMapper.getClassStudentNumbers(className));
        studentNumberList.addAll(teacherMapper.getStudentNumbers(course.getCourseNumber()));
        // 获取学生对象集合
        List<Student> studentList = new ArrayList<>();
        for (String studentNumber : studentNumberList){
            studentList.add(teacherMapper.selectStudent(studentNumber));
        }
        // 为学生们构造签到集合
        SignInfo signInfo = new SignInfo();
        signInfo.setCourseNumber(course.getCourseNumber());
        signInfo.setTeacherName(course.getTeacherName());
        // 生成验证码
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder result = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(characters.length());
            result.append(characters.charAt(index));
        }

        String code = result.toString();
        System.out.println("验证码" + code);
        // 遍历每个学生
        for (Student student : studentList){
            signInfo.setSNumber(student.getSNumber());
            signInfo.setSName(student.getSName());
            signInfo.setCode(code);
            teacherMapper.postSignIn(signInfo);
            s++;
        }
        return s > 0;
    }

    // 查看所教的课程
    @Override
    public List<Course> getTeachCourses(String teacherNumber) {

        List<Course> courseList = new ArrayList<>();
        // 获取公共课程和选修课程，添加到课程列表，一起返回
        List<Course> publicCourse = teacherMapper.getTeachPublicCourse(teacherNumber);
        List<Course> takeCourse = teacherMapper.getTeachTakeCourse(teacherNumber);
        courseList.addAll(publicCourse);
        courseList.addAll(takeCourse);
        return courseList;
    }

    // 查看某课程发布的签到记录
    @Override
    public IPage<SignInfo> getSignInfo(Integer currentPage, Integer size, String courseNumber) {
        Page<SignInfo> pagerequest = new Page<>(currentPage,size);
        IPage<SignInfo>  signInfoIpage = teacherMapper.getSignInfos(pagerequest,courseNumber);
        return signInfoIpage;

    }

    // 查看签到的学生
    @Override
    public IPage<SignInfo> getSignStudents(Integer currentPage, Integer size, String postTime) {
        Page<SignInfo> pagerequest = new Page<>(currentPage,size);

        IPage<SignInfo>  sign = teacherMapper.getSignStudents(pagerequest,postTime);
        return sign;
    }

    // 查看未签到的学生
    @Override
    public IPage<SignInfo> getUnSignStudents(Integer currentPage, Integer size,String postTime) {
        Page<SignInfo> pagerequest = new Page<>(currentPage,size);
        IPage<SignInfo>  unSign = teacherMapper.getUnSignStudents(pagerequest,postTime);
        return unSign;
    }


    // 排课
    @Override
    public boolean insertCourse(Course course) {
        // 判断课程时间地点是否冲突
        int checkTakeCourse = teacherMapper.checkTakeCourse(course.getLocation(),course.getStartTime(),course.getEndTime());
        int checkPublicCourse = teacherMapper.checkPublicCourse(course.getLocation(),course.getStartTime(),course.getEndTime());
        if (checkPublicCourse > 0 || checkTakeCourse > 0){
            return false;
        }
        // 判断是公共课还是选修课
        if (teacherMapper.checkPublic(course.getCourseNumber()) > 0){   // 是公共课
            return teacherMapper.insertPublicCourse(course) > 0;
        }else if (teacherMapper.checkTake(course.getCourseNumber()) > 0){    // 是选修课
            return teacherMapper.insertTakeCourse(course) > 0;
        }else{
            return false;
        }
    }

    // 获取某门课程的课程情况
    @Override
    public IPage<Course> getOneCourseInfo(Integer currentPage, Integer size, String courseNumber) {
        // 判断课程号是公共课还是选修课
        if (teacherMapper.checkPublic(courseNumber) > 0){    // 是公共课
            Page<Course> pagerequest = new Page<>(currentPage,size);
            IPage<Course>  courseIPage1 = teacherMapper.getOnePublicCourse(pagerequest,courseNumber);
            return courseIPage1;
        }else if (teacherMapper.checkTake(courseNumber) > 0){    // 是选修课
            Page<Course> pagerequest = new Page<>(currentPage,size);
            IPage<Course>  courseIPage2 = teacherMapper.getOneTakeCourse(pagerequest,courseNumber);
            return courseIPage2;
        }else{
            return null;
        }


    }

    // 调整某堂课程
    @Override
    public boolean updateCourse(Course course) {
        // 判断是公共课还是选修课
        if (teacherMapper.checkPublic(course.getCourseNumber()) > 0){   // 是公共课
           return teacherMapper.updatePublicCourse(course) > 0;
        }else if (teacherMapper.checkTake(course.getCourseNumber()) > 0){    // 是选修课
           return teacherMapper.updateTakeCourse(course) > 0;
        }else{
            return false;
        }
    }

    // 通过时间查询选修课
    @Override
    public IPage<TakeCourse> selectTakeCourseByDate(Integer currentPage, Integer size, String time, String courseNumber) {
        if (courseNumber == null) {
            return null;
        }
        Page<TakeCourse> pageRequest = new Page<>(currentPage, size);
        IPage<TakeCourse> takeCourseIPage = takeCourseMapper.selectByStartTime(pageRequest, time, courseNumber);

        // 如果开始时间的查询结果为空，则查询结束时间
        if (takeCourseIPage == null || takeCourseIPage.getRecords().isEmpty()) {
            takeCourseIPage = takeCourseMapper.selectByEndTime(pageRequest, time, courseNumber);
        }

        return takeCourseIPage;
    }

    // 通过时间查询公共课
    @Override
    public IPage<PublicCourse> selectPublicCourseByDate(Integer currentPage, Integer size, String time, String courseNumber) {
        if (courseNumber == null) {
            return null;
        }
        Page<PublicCourse> pageRequest = new Page<>(currentPage, size);
        IPage<PublicCourse> publicCourseIPage = publicCourseMapper.selectByStartTime(pageRequest, time, courseNumber);

        // 如果开始时间的查询结果为空，则查询结束时间
        if (publicCourseIPage == null || publicCourseIPage.getRecords().isEmpty()) {
            publicCourseIPage = publicCourseMapper.selectByEndTime(pageRequest, time, courseNumber);
        }

        return publicCourseIPage;
    }

}
